package com.example.androidgeneric;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;

import android.util.Log;

import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.example.androidgeneric.VolleyPostJsonResult.onResultValue;

public class ServerJsonResult<T extends Serializable> implements onResultValue<T> {

	private RequestQueue queue;
	
	private VolleyPostJsonResult<T> onResult;
	
	private Type type;

	public interface onServerRequest<T extends Serializable> {
		public void onResult(T result);

		public void onStartConnectionUI();

		public void onEndConnection();

		public void onError(VolleyError err);
	}

	public onServerRequest<T> serverRequest;

	public ServerJsonResult(String URL, RequestQueue queue, Type DataType) {
		this.queue = queue;
		this.type = DataType;
		this.onResult = new VolleyPostJsonResult<T>(type, URL, listener,
				errorListener);
		this.onResult.setOnResult(this);
		this.type = DataType;
		Log.d("DataType", type.toString());
	}

	public void setParam(HashMap<String, String> param) {
		onResult.setInput(param);
	}

	public void setOnServerRequest(onServerRequest<T> request) {
		serverRequest = request;
	}

	public void commit() {
		serverRequest.onStartConnectionUI();
		queue.add(onResult);
	}

	private Listener<String> listener = new Listener<String>() {

		@Override
		public void onResponse(String result) {
			serverRequest.onEndConnection();
		}
	};

	private ErrorListener errorListener = new ErrorListener() {

		@Override
		public void onErrorResponse(VolleyError err) {
			serverRequest.onEndConnection();
			serverRequest.onError(err);
		}
	};

	@Override
	public void onJsonResult(ArrayList<T> result) {
		serverRequest.onResult(result.get(0));
	}
}
